package com.ruoyi.feike.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DayUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.dto.NewSumDTO;
import com.ruoyi.feike.domain.dto.WfsLimitSetUpdto;
import com.ruoyi.feike.domain.vo.ContractRecord;
import com.ruoyi.feike.domain.vo.DealerformationVO;
import com.ruoyi.feike.domain.vo.KeepVO;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Api(value = "WfsLimitSetUp流程页", tags = "WfsLimitSetUp流程页", description = "年审列表下面用")
@RestController
@RequestMapping("/feike/wfsLimitSetUp")
public class WfsLimitSetUpController extends BaseController {

	@Value("${wfs.url}")
	private String wfsUrl;

	@Autowired
	private NewSumKeepMapper newSumKeepMapper;

	@Autowired
	private  IHLimitSetupResultService limitSetupResultService;
	@Autowired
	private IWfsLimitSetUpService wfsLimitSetUpService;
	@Autowired
	private IInsuranceCalculationService insuranceCalculationService;
	@Autowired
	private IPaidSumService paidSumService;
	@Autowired
	private INewSumService newSumService;
	@Autowired
	private IKeepTempSerivce  keepTempSerivce;

	@Autowired
	private IDealerInformationService dealerInformationService;

	@Autowired
	private IDepositCalculationService depositCalculationService;
	@Autowired
	private INewSumKeepService newSumKeepService;

	@Autowired
	private BasicInformationMapper basicInformationMapper;

	@Autowired
	private ILimitActiveProposalService limitActiveProposalService;

	@Autowired
	private LimitActiveProposalMapper limitActiveProposalMapper;

	@Autowired
	private DepositCalculationMapper depositCalculationMapper;

	@Autowired
	private DealercodeContractFilingMapper dealercodeContractFilingMapper;

	@Autowired
	private ContractRecordMapper contractRecordMapper;

	@Autowired
	private HExpiryDateHisMapper expiryDateHisMapper;

	@Autowired
	private IAnnualReviewyService annualReviewyService;


	@Value("${uat.fileName1}")
	private String fileName1;

	@Value("${uat.fileName2}")
	private String fileName2;

	@ApiOperation("发起WfsLimitSetUp流程")
	@Log(title = "feike", businessType = BusinessType.INSERT)
	@PostMapping
	//public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
	public AjaxResult add(@RequestBody WfsLimitSetUpdto wfsLimitSetUpdto) {
		return toAjax(wfsLimitSetUpService.insertWfsLimitSetUp(wfsLimitSetUpdto));
	}

	@ApiOperation("修改WfsLimitSetUp流程")
	@Log(title = "feike", businessType = BusinessType.UPDATE)
	@PostMapping("/update")
	public AjaxResult update(@RequestBody WfsLimitSetUpdto wfsLimitSetUpdto) {
		String resp = wfsLimitSetUpService.updateWfsLimitSetUp(wfsLimitSetUpdto);
		if(!resp.equals("1")){
			return AjaxResult.error(500,resp);
		}
		return toAjax(1);
	}


	@GetMapping(value = { "/changInsuranceHistory/{instanceId}" })
	public AjaxResult changInsuranceHistory(@PathVariable(value = "instanceId", required = false) String instanceId)
	{
		AjaxResult ajax = AjaxResult.success();
		List<NewSumKeep>  newSumKeeps  = null;
		if(StringUtils.isNotEmpty(instanceId)) {
			NewSumKeep newSumKeep = new NewSumKeep();
			newSumKeep.setInstanceId(instanceId);
			List<NewSumKeep> insuranceHistory = newSumKeepService.selectInsuranceHistory(newSumKeep);
			if(insuranceHistory != null &&insuranceHistory.size()>0){
				NewSumKeep newSumKeep2 = new NewSumKeep();
				newSumKeep2.setDealerName(insuranceHistory.get(0).getDealerName());
				newSumKeep2.setSector(insuranceHistory.get(0).getSector());
				newSumKeeps = newSumKeepMapper.selectNewSumKeepList4(newSumKeep2);
				if(newSumKeeps!=null &&  newSumKeeps.size()> 0 ){
					for (NewSumKeep sumKeep : insuranceHistory) {
						newSumKeepService.deleteInsuranceHistoryById(sumKeep.getId());
					}
					for (NewSumKeep sumKeep : newSumKeeps) {
						sumKeep.setInstanceId(instanceId);
						newSumKeepService.insertInsuranceHistory(sumKeep);
					}
				}
			}
			ajax.put("insuranceHistory", newSumKeeps);
		}
		return ajax;
	}

	@ApiOperation("刷新WfsLimitSetUp数据")
	@Log(title = "feike", businessType = BusinessType.UPDATE)
	@GetMapping("/refreshData/{instanceId}")
	public AjaxResult refreshData(@PathVariable("instanceId") String instanceId) {
		//return toAjax(wfsLimitSetUpService.insertWfsLimitSetUp(wfsLimitSetUpdto));
		List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByByInstanceId(instanceId);
		for (BasicInformation basicInformation : basicInformations) {
			if(basicInformation.getDealerNameCN()!=null){
				ArrayList<DealerInformation> dealerInformations = new ArrayList<>();
				DealerInformation dealerInformation = new DealerInformation();
				dealerInformation.setDealerName(basicInformation.getDealerNameCN());
				dealerInformations.add(dealerInformation);
				List<DealerformationVO> list = dealerInformationService.listByName(dealerInformations);
				if(list!=null && list.size()>0){
					DealerformationVO dealerformationVO = list.get(0);
					//更新
					BasicInformation basicInformation1 = new BasicInformation();
					basicInformation1.setId(basicInformation.getId());
					basicInformation1.setDealerNameCN(dealerformationVO.getDealerNameCN());

					List dealerCodeFromWFS = dealerformationVO.getDealerCodeFromWFS();
					if(null != dealerCodeFromWFS &&dealerCodeFromWFS.size()>0 ){
						StringBuilder dealerCode = new StringBuilder();
						for (int i = 0; i < dealerCodeFromWFS.size(); i++) {
							dealerCode.append(dealerCodeFromWFS.get(i));
							dealerCode.append(",");
						}
						if (!StringUtils.isEmpty(dealerCode)) {
							dealerCode.deleteCharAt(dealerCode.length() - 1);
							basicInformation1.setDealerCodeFromWFS(dealerCode.toString());
						}
					}
					List sector = dealerformationVO.getSector();
					if(null != sector && sector.size()>0){
						StringBuilder sectorStr = new StringBuilder();
						for (int i = 0; i < sector.size(); i++) {
							sectorStr.append(sector.get(i));
							sectorStr.append(",");
						}
						if (!StringUtils.isEmpty(sectorStr)) {
							sectorStr.deleteCharAt(sectorStr.length() - 1);
							basicInformation1.setSector(sectorStr.toString());
						}
					}
					List dealerCodeFromManufacturer = dealerformationVO.getDealerCodeFromManufacturer();
					if(null != dealerCodeFromManufacturer && dealerCodeFromManufacturer.size()>0){
						StringBuilder manufacturer = new StringBuilder();
						for (int i = 0; i < dealerCodeFromManufacturer.size(); i++) {
							manufacturer.append(dealerCodeFromManufacturer.get(i));
							manufacturer.append(",");
						}
						if (!StringUtils.isEmpty(manufacturer)) {
							manufacturer.deleteCharAt(manufacturer.length() - 1);
							basicInformation1.setDealerCodeFromManufacturer(manufacturer.toString());
						}
					}
					List<Map<String, Object>> shareholdersAndShare = dealerformationVO.getShareholdersAndShare();
					if(null != shareholdersAndShare && shareholdersAndShare.size()>0){
						Map<String, Object> stringObjectMap = shareholdersAndShare.get(0);
						StringBuilder shareStr = new StringBuilder();
						String s1 = (String) stringObjectMap.get("shareholdersCn");
						String s2 = (String) stringObjectMap.get("shareholdersEn");
						String s3= (String) stringObjectMap.get("share");
						shareStr.append(s1).append(",");
						shareStr.append(s2).append(",").append(s3);
						basicInformation1.setShareholders(shareStr.toString());
					}
					basicInformation1.setRegisteredAddressCN(dealerformationVO.getRegisteredAddressCN());
					basicInformation1.setRegisteredAddressEN(dealerformationVO.getRegisteredAddressEN());
					basicInformation1.setLegalRepresentativeCN(dealerformationVO.getLegalRepresentativeCN());
					basicInformation1.setLegalRepresentativeEN(dealerformationVO.getLegalRepresentativeEN());
					if(dealerformationVO.getIncorporationDate()!=null){
						basicInformation1.setIncorporationDate(dealerformationVO.getIncorporationDate().toString());
					}else{
						basicInformation1.setIncorporationDate(null);
					}
					if(dealerformationVO.getJoinSectorDealerNetworkDate()!=null){
						basicInformation1.setJoinSectorDealerNetworkDate(dealerformationVO.getJoinSectorDealerNetworkDate().toString());
					}else{
						basicInformation1.setJoinSectorDealerNetworkDate(null);
					}
					basicInformation1.setRegisteredCapital(dealerformationVO.getRegisteredCapital());
					if(dealerformationVO.getPaidupCapital()!=null){
						basicInformation1.setPaidupCapital(dealerformationVO.getPaidupCapital().toString());
					}else{
						basicInformation1.setPaidupCapital(null);
					}
					basicInformation1.setGm(dealerformationVO.getGm());
					if(dealerformationVO.getRelatedWorkingExperience()!=null){
						basicInformation1.setRelatedWorkingExperience(Integer.valueOf(dealerformationVO.getRelatedWorkingExperience().toString()));

					}else{
						basicInformation1.setRelatedWorkingExperience(null);
					}
					int i = basicInformationMapper.updateBasicInformation(basicInformation1);
					System.out.println("basicInformation更新数量为"+i);
				}

			}

		}
		//Proposal信息更新
		List<LimitActiveProposal> limitActiveProposalList = limitActiveProposalMapper.getListByInstanceId(instanceId);
		if(limitActiveProposalList!=null && limitActiveProposalList.size()>0){
			for (LimitActiveProposal limitActiveProposal : limitActiveProposalList) {
				DepositDecreaseDTO depositDecreaseDTO = new DepositDecreaseDTO();
				String dealerCode = limitActiveProposal.getDealerCode();
				ArrayList<String[]> lists = new ArrayList<>();
				String [] arr = new String[]{dealerCode};
				lists.add(arr);
				depositDecreaseDTO.setDealerCodeArr(lists);
				Map<String, Object> limitActivationProposalMap = getLimitActivationProposal1(depositDecreaseDTO);
				List<LimitActiveProposal> limitActiveProposals  = (List<LimitActiveProposal>)limitActivationProposalMap.get("limitActiveProposals");
				for (LimitActiveProposal activeProposal : limitActiveProposals) {
					if(activeProposal.getDealerCode().equals(limitActiveProposal.getDealerCode()) && activeProposal.getLimitType().equals(limitActiveProposal.getLimitType())){
						activeProposal.setId(limitActiveProposal.getId());
						activeProposal.setInstanceId(limitActiveProposal.getInstanceId());
						limitActiveProposalMapper.updateLimitActiveProposal(activeProposal);
					}
				}
				List<DepositCalculation> depositCalculations    = (List<DepositCalculation>)limitActivationProposalMap.get("depositCalculations");
				List<DepositCalculation> listByInstances = depositCalculationMapper.getListByInstanceId(instanceId);
				for (DepositCalculation listByInstance : listByInstances) {
					for (DepositCalculation depositCalculation : depositCalculations) {
						if(listByInstance.getDealerCode().equals(depositCalculation.getDealerCode())&& listByInstance.getLimitType().equals(depositCalculation.getLimitType())){
							depositCalculation.setId(listByInstance.getId());
							depositCalculation.setInstanceId(listByInstance.getInstanceId());
							depositCalculationMapper.updateDepositCalculation(depositCalculation);
						}
					}
				}
			}
		}
		return  AjaxResult.success();
	}

	@ApiOperation("Limit Activation Proposal")
	@PostMapping("/limitActivationProposal")
	public AjaxResult getLimitActivationProposal(@RequestBody DepositDecreaseDTO depositDecreaseDTO) {
		return AjaxResult.success(getLimitActivationProposal1(depositDecreaseDTO));
	}

	@ApiOperation("Limit Activation Proposal")
	@PostMapping("/updateLimitActivationProposal")
	public AjaxResult getLimitActivationProposal3(@RequestBody DepositDecreaseDTO depositDecreaseDTO) {
		return AjaxResult.success(getLimitActivationProposal2(depositDecreaseDTO));
	}

	@ApiOperation("Limit Activation Proposal")
	@PostMapping("/refurbish")
	public AjaxResult refurbish(@RequestBody DepositDecreaseDTO depositDecreaseDTO) {
		return AjaxResult.success(getLimitActivationProposal4(depositDecreaseDTO));
	}

	@ApiOperation("get filesName")
	@GetMapping("/getFilesName")
	public AjaxResult getFilesName() {
		Map<String, Object> result = new HashMap<>();
		result.put("fileName1",fileName1);
		result.put("fileName2",fileName2);
		return AjaxResult.success(result);
	}

	public Map<String, Object> getLimitActivationProposal1(DepositDecreaseDTO depositDecreaseDTO){

		JSONObject jsonObject = new JSONObject();
		Map<String, Object> result = new HashMap<>();
		List<LimitActiveProposal> limitActiveProposals = new ArrayList<>();
		List<DepositCalculation> depositCalculations = new ArrayList<>();
		String[] dealerCodes = depositDecreaseDTO.getDealerCodeArr().get(0);
		List<String[]> strList = new ArrayList<String[]>();

		String dealerCode = "";
		String dealerStatus ="";
		//String dealerCode = "K55105";
		DealerInformation dealerInformation = new DealerInformation();
		dealerInformation.setDealerName(depositDecreaseDTO.getDealerNames());
		dealerInformation.setMake(depositDecreaseDTO.getSector());
		List<DealerInformation> dealerInformations = dealerInformationService.selectDealerInformationList2(dealerInformation);
		if (dealerInformations != null && dealerInformations.size() > 0) {
			dealerInformation = dealerInformations.get(0);
			String[] str = new String[1];
			dealerCode = dealerInformation.getDealerCode();
			str[0] = dealerInformation.getDealerCode();
			strList.add(str);
		}
		jsonObject.put("DealerCode", strList);
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		System.out.println(jsonObject.toString());
		HttpPost httpPost = new HttpPost(wfsUrl + "CreditInfo");
		HttpPost httpPost2 = new HttpPost(wfsUrl + "SuspenseInfo");
		httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
		httpPost2.addHeader("Content-Type", "application/json;charset=UTF-8");
		StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
		entity.setContentType("application/json;charset=UTF-8");
		entity.setContentEncoding("UTF-8");
		httpPost.setEntity(entity);
		httpPost.setHeader("Accept", "application/json, text/plain, */*");
		httpPost.setHeader("Accept-Encoding", "gzip, deflate");
		httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38");
		httpPost2.setEntity(entity);
		httpPost2.setHeader("Accept", "application/json, text/plain, */*");
		httpPost2.setHeader("Accept-Encoding", "gzip, deflate");
		httpPost2.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
		httpPost2.setHeader("Connection", "keep-alive");
		httpPost2.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38");
		Map<String, Object> objectList = new HashMap<>();
		Map<String, Object> objectList2 = new HashMap<>();
		try {
			Map<String, Object> stringObjectHashMap = new HashMap<>();
			stringObjectHashMap.put("Deposit",0);
			stringObjectHashMap.put("CBDeposit",0);
			stringObjectHashMap.put("PartDeposit",0);
			stringObjectHashMap.put("UsedDeposit",0);
			log.info("发送");
			HttpResponse response = httpClient.execute(httpPost);
			String responseStr = EntityUtils.toString(response.getEntity());
			HttpResponse response2 = httpClient.execute(httpPost2);
			String responseStr2 = EntityUtils.toString(response2.getEntity());
			log.info("WFS外部接口数据返回结果=[{}]", responseStr);
			log.info("WFS外部接口数据返回结果2=[{}]", responseStr2);
			objectList = JSONObject.parseObject(responseStr, Map.class);
			objectList2 = JSONObject.parseObject(responseStr2, Map.class);
			if (Integer.valueOf(String.valueOf(objectList.get("Code"))) == 200) {
				Map data = (Map) JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(objectList.get("Data"))).get(0))).get(0)), Map.class).get("CreditInfo"))).get(0);
				List creditDet = (List) data.get("CreditDet");
				Map data2 = (Map)JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(objectList.get("Data"))).get(0))).get(0)), Map.class)));
				if(data2!=null){
					dealerStatus = (String)data2.get("DealerStatus");
				}
				System.out.println(data2);
				try{
					stringObjectHashMap = JSONObject.parseObject(String.valueOf(JSONObject.parseObject(String.valueOf(JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(objectList2.get("Data"))).get(0))).get(0))).get("SuspenseInfo")), Map.class);
				}catch (Exception e){
					e.printStackTrace();
				}
				stringObjectHashMap.put("Deposit",stringObjectHashMap.get("Deposit") != null ? stringObjectHashMap.get("Deposit") : 0);
				stringObjectHashMap.put("CBDeposit",stringObjectHashMap.get("Deposit") != null ? stringObjectHashMap.get("CBDeposit") : 0);
				stringObjectHashMap.put("PartDeposit",stringObjectHashMap.get("PartDeposit") != null ? stringObjectHashMap.get("PartDeposit") : 0);
				stringObjectHashMap.put("UsedDeposit",stringObjectHashMap.get("UsedDeposit") != null ? stringObjectHashMap.get("UsedDeposit") : 0);
				List<Map<String, Object>> creditDets = creditDet;
				//是否存在NORMAL

				//NORMAL 数据

				Map<String, Object> normalData = null;
				Boolean flag = true;
				for (int i = 0; i < creditDets.size(); i++) {
					Map<String, Object> objectMap = creditDets.get(i);
					if(objectMap.get("LimitType").toString().equalsIgnoreCase("NORMAL")){
						normalData = creditDets.get(i);
						break;
					}
				}

				for (int i = 0; i < creditDets.size(); i++) {
					Map<String, Object> objectMap = creditDets.get(i);
					LimitActiveProposal limitActiveProposal = new LimitActiveProposal();
					limitActiveProposal.setDealerName(dealerInformation.getDealerName());
					limitActiveProposal.setDealerCode(dealerCode);
					limitActiveProposal.setDealerStatus(dealerStatus);
					limitActiveProposal.setSector(dealerInformation.getMake());

					limitActiveProposal.setLimitType(String.valueOf(objectMap.get("LimitType")));
					limitActiveProposal.setCurrentCreditLimit(Long.valueOf(String.valueOf(objectMap.get("CreditLimit"))));

					//激活额度
					limitActiveProposal.setCurrentActiveLimit(String.valueOf(objectMap.get("ActiveLimit")));



					//设置保证金比例
					if(objectMap.get("LimitType").toString().equalsIgnoreCase("CB")){
						limitActiveProposal.setApprovedCashDeposit(String.valueOf(objectMap.get("SecurityRatio")));
					}else if( objectMap.get("LimitType").toString().equalsIgnoreCase("MGR") ){
						//limitActiveProposal.setApprovedCashDeposit("");
					}else if(ObjectUtil.isNotEmpty(normalData) && (objectMap.get("LimitType").toString().equalsIgnoreCase("NORMAL") || objectMap.get("LimitType").toString().equalsIgnoreCase("DEMO") || objectMap.get("LimitType").toString().equalsIgnoreCase("USED"))){
						limitActiveProposal.setApprovedCashDeposit(String.valueOf(normalData.get("SecurityRatio")));
					}else if(ObjectUtil.isNotEmpty(normalData) && (objectMap.get("LimitType").toString().equalsIgnoreCase("TEMP") || objectMap.get("LimitType").toString().equalsIgnoreCase("PART"))){
						limitActiveProposal.setApprovedCashDeposit(String.valueOf(objectMap.get("SecurityRatio")));
					}


					limitActiveProposal.setOs(String.valueOf(objectMap.get("ActiveOS")));
					if(!StringUtils.isEmpty(String.valueOf(objectMap.get("ActiveExpireDate")))){
						String activeExpireDate = String.valueOf(objectMap.get("ActiveExpireDate"));
						String replace = activeExpireDate.replace("/", "-");
						limitActiveProposal.setCurrentActiveLimitExpiryDate(replace);
					}else{
						limitActiveProposal.setCurrentActiveLimitExpiryDate(null);
					}
					if (objectMap.get("LimitType").equals("NORMAL") || objectMap.get("LimitType").equals("DEMO") || objectMap.get("LimitType").equals("TEMP")) {
						limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("Deposit")));
					} else if (objectMap.get("LimitType").equals("CB")) {
						limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("CBDeposit")));
					}else if (objectMap.get("LimitType").equals("PART")){
						limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("PartDeposit")));
					}else if (objectMap.get("LimitType").equals("USED")){
						limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("UsedDeposit")));
					}
					if (StringUtils.isNotEmpty(limitActiveProposal.getApprovedCashDeposit())) {
						if(StringUtils.isNotEmpty(limitActiveProposal.getApprovedCashDeposit()) && StringUtils.isNotEmpty(limitActiveProposal.getProposalCashDeposit())){
							//Double aDouble = Double.valueOf(limitActiveProposal.getApprovedCashDeposit().replace("%", ""));
							String replace = limitActiveProposal.getApprovedCashDeposit().replace("%", "");
							BigDecimal bigDecimal2 = new BigDecimal(limitActiveProposal.getProposalCashDeposit());
							BigDecimal bigDecimal3 = new BigDecimal(replace).setScale(4, BigDecimal.ROUND_CEILING);
							BigDecimal bigDecimal4 = bigDecimal2.divide(bigDecimal3,4,BigDecimal.ROUND_HALF_UP);
							BigDecimal bigDecimal5 = bigDecimal4.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
							//BigDecimal bigDecimal = new BigDecimal(limitActiveProposal.getProposalCashDeposit()).divide(new BigDecimal(aDouble)).setScale(2, BigDecimal.ROUND_HALF_UP);
							//BigDecimal bigDecimal1 = bigDecimal.divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);


							limitActiveProposal.setLimitCoveredDeposit(bigDecimal5.toString());
						}
					} else {
						limitActiveProposal.setLimitCoveredDeposit("");
					}
					limitActiveProposal.setProposedStart(new Date());
					if ((objectMap.get("LimitType").toString().equals("DEMO") ||  objectMap.get("LimitType").toString().equals("CB")) && ObjectUtil.isNotEmpty(normalData)){
						if(StringUtils.isNotEmpty(normalData) &&  normalData.get("ExpiryDate")!=null){
							limitActiveProposal.setProposedEnd(new Date(String.valueOf(normalData.get("ExpiryDate"))));
							limitActiveProposal.setProposedExpiredDate(new Date(String.valueOf(normalData.get("ExpiryDate"))));
							limitActiveProposal.setFlag(1);
						}
					}else if (objectMap.get("LimitType").toString().equals("PART") && ObjectUtil.isNotEmpty(normalData)){
						if(StringUtils.isNotEmpty(normalData) &&  normalData.get("ExpiryDate")!=null) {
							limitActiveProposal.setProposedEnd(new Date(String.valueOf(normalData.get("ExpiryDate"))));
							limitActiveProposal.setProposedExpiredDate(new Date(String.valueOf(normalData.get("ExpiryDate"))));
							limitActiveProposal.setFlag(1);
						}
					}
					else if (StringUtils.isNotEmpty(String.valueOf(objectMap.get("ExpiryDate")))){
						limitActiveProposal.setProposedEnd(new Date(String.valueOf(objectMap.get("ExpiryDate"))));
						limitActiveProposal.setProposedExpiredDate(new Date(String.valueOf(objectMap.get("ExpiryDate"))));
						limitActiveProposal.setFlag(1);
					}
					//流程九合同字段取值，上一类不涉及初始化报表，根据线上来，下一类涉及线下数据，但线下数据不完整

					if(objectMap.get("LimitType") !=null && String.valueOf(objectMap.get("LimitType")).equals("PART")){
						ContractRecord contractRecord = new ContractRecord();
						contractRecord.setDealername(dealerInformation.getDealerName());
						contractRecord.setSector(dealerInformation.getMake());
						contractRecord.setContracttype("试乘试驾车抵押合同（E已更改）");
						List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordListRecentlyEffectiveDateByPart(contractRecord);
						if(StringUtils.isNotEmpty(contractRecords)){
							if(StringUtils.isNotEmpty(contractRecords.get(0).getPartsAmount())) {
								limitActiveProposal.setContractFacilityAmount(contractRecords.get(0).getPartsAmount());
							}
							if(StringUtils.isNotNull(contractRecords.get(0).getExpirydate())) {
								limitActiveProposal.setContractExpireDate(contractRecords.get(0).getExpirydate());
							}
							if(StringUtils.isNotEmpty(contractRecords.get(0).getPartsDepositRatio())) {
								limitActiveProposal.setContractDepositRatio(contractRecords.get(0).getPartsDepositRatio());
							}
							if(StringUtils.isNotEmpty(contractRecords.get(0).getFileUrl())){
								limitActiveProposal.setContractHyperlink(contractRecords.get(0).getFileUrl());
							}
							Date effectiveDate = contractRecords.get(0).getEffectivedate();
							String status = contractRecords.get(0).getStatus();
							if(effectiveDate!=null && status != null && status.equals("盖章")){
								limitActiveProposal.setContractStatus("已签回");
							}else{
								limitActiveProposal.setContractStatus("未签回");
							}
						}
					}else{
						ContractRecord contractRecord = new ContractRecord();
						contractRecord.setDealername(dealerInformation.getDealerName());
						contractRecord.setSector(dealerInformation.getMake());
						contractRecord.setLimitType(String.valueOf(objectMap.get("LimitType")));
						contractRecord.setContracttype("试乘试驾车抵押合同（E已更改）");
						List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordListRecentlyEffectiveDate(contractRecord);
						if(StringUtils.isNotEmpty(contractRecords)){
							if(StringUtils.isNotEmpty(contractRecords.get(0).getFacilityamount())) {
								limitActiveProposal.setContractFacilityAmount(contractRecords.get(0).getFacilityamount());
							}
							if(StringUtils.isNotNull(contractRecords.get(0).getExpirydate())) {
								limitActiveProposal.setContractExpireDate(contractRecords.get(0).getExpirydate());
							}
							if(StringUtils.isNotEmpty(contractRecords.get(0).getDeposit())) {
								limitActiveProposal.setContractDepositRatio(contractRecords.get(0).getDeposit());
							}
							if(StringUtils.isNotEmpty(contractRecords.get(0).getFileUrl())){
								limitActiveProposal.setContractHyperlink(contractRecords.get(0).getFileUrl());
							}
							Date effectiveDate = contractRecords.get(0).getEffectivedate();
							String status = contractRecords.get(0).getStatus();
							if(effectiveDate!=null && status != null && status.equals("盖章")){
								limitActiveProposal.setContractStatus("已签回");
							}else{
								limitActiveProposal.setContractStatus("未签回");
							}
						}
					}
					DepositCalculation depositCalculation = new DepositCalculation();
					depositCalculation.setDealerName(limitActiveProposal.getDealerName());
					depositCalculation.setDealerCode(limitActiveProposal.getDealerCode());
					depositCalculation.setSector(limitActiveProposal.getSector());
					depositCalculation.setLimitType(limitActiveProposal.getLimitType());
					depositCalculation.setCurrentAmount(StringUtils.isNotEmpty(String.valueOf(limitActiveProposal.getProposalCashDeposit()))?String.valueOf(limitActiveProposal.getProposalCashDeposit()):"");
					// depositCalculation.setProposedAmount(String.valueOf(Long.valueOf(limitActiveProposal.getProposalActiveLimit()) * Double.valueOf(limitActiveProposal.getApprovedCashDeposit().replace("%", ""))));
					// depositCalculation.setGap(String.valueOf(Double.valueOf(depositCalculation.getProposedAmount()) - Double.valueOf(depositCalculation.getCurrentAmount())));
					depositCalculations.add(depositCalculation);

/*					String DateTempStr ="2024-10-30";
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					try {
						Date parse = sdf.parse(DateTempStr);
						limitActiveProposal.setProposedEnd(parse);
					}catch (Exception e){
						e.printStackTrace();
					}*/


					limitActiveProposals.add(limitActiveProposal);
				}
			}
			log.info("WFS外部接口数据返回JSON结果=[{}]", JSON.toJSONString(responseStr));

		} catch (IOException e) {
			e.printStackTrace();
		}

		NewSumKeep sumKeep = new NewSumKeep();
		sumKeep.setDealerName(dealerInformation.getDealerName());
		sumKeep.setSector(dealerInformation.getMake());
		List<NewSumKeep> newSumKeeps = newSumKeepService.selectNewSumKeepList4(sumKeep);
		result.put("insuranceHistory",newSumKeeps);
		BigDecimal rate = null;
		if(newSumKeeps!=null && newSumKeeps.size()>0){
			String planRate = newSumKeeps.get(0).getPlanRate();
			if(StringUtils.isNotEmpty(planRate) && !planRate.equals("-")){
				rate = new BigDecimal(planRate);
			}
		}
		if(rate !=null){
			BigDecimal multiply = rate.multiply(new BigDecimal(100));
			BigDecimal bigDecimal = multiply.setScale(7, RoundingMode.HALF_UP);
			String s = Arith.removeZeros(bigDecimal.toString());
			result.put("planRate",s+"%");
		}else{
			result.put("planRate","");
		}



		List<DepositCalculation> calculations = new ArrayList<>();

		for (DepositCalculation depositCalculation : depositCalculations) {
			if(depositCalculation.getLimitType().equals("NORMAL") || depositCalculation.getLimitType().equals("DEMO") || depositCalculation.getLimitType().equals("TEMP")){
				calculations.add(depositCalculation);
			}
		}

		if(calculations.size() >= 2){
			Iterator<DepositCalculation> iterator = depositCalculations.iterator();

			while(iterator.hasNext()) {
				DepositCalculation next = iterator.next();

				if (next.getLimitType().equals("NORMAL") || next.getLimitType().equals("DEMO") || next.getLimitType().equals("TEMP")) {
					iterator.remove();
				}
			}

			DepositCalculation depositCalculation = calculations.get(0);
			depositCalculation.setLimitType("NORMAL/DEMO/TEMP");
			depositCalculations.add(depositCalculation);
		}

//		int proposalsSize = limitActiveProposals.size();
//		int calculationsSize = depositCalculations.size();
//
//
//		List<LimitActiveProposal> limitActiveProposals2 = new ArrayList<>();
//		List<DepositCalculation> depositCalculations2 = new ArrayList<>();
//
//		for (LimitActiveProposal limitActiveProposal : limitActiveProposals) {
//
//		}
//
//		for (DepositCalculation depositCalculation : depositCalculations) {
//			if(depositCalculation.getLimitType().equalsIgnoreCase("NORMAL")){
//
//			}
//
//		}

		for (LimitActiveProposal limitActiveProposal : limitActiveProposals) {
			limitActiveProposal.setSort(typeSort(limitActiveProposal.getLimitType()));
			/*//日期查询 先查询已完成的 在查询历史表
			Date currentActiveLimitExpiryDate =null;
			List<LimitActiveProposal> limitActiveProposals1 = limitActiveProposalService.selectCurrentActiveLimitExpiryDate(limitActiveProposal);
			if(limitActiveProposals1!=null && limitActiveProposals1.size()>0){
				currentActiveLimitExpiryDate = limitActiveProposals1.get(0).getCurrentActiveLimitExpiryDate();
			}else{
				HExpiryDateHis hExpiryDateHis = new HExpiryDateHis();
				hExpiryDateHis.setSector(limitActiveProposal.getSector());
				hExpiryDateHis.setDealername(limitActiveProposal.getDealerName());
				hExpiryDateHis.setLimittype(limitActiveProposal.getLimitType());
				List<HExpiryDateHis> hExpiryDateHis1 = expiryDateHisMapper.selectHExpiryDateHisList(hExpiryDateHis);
				if(hExpiryDateHis1 !=null && hExpiryDateHis1.size()>0){
					currentActiveLimitExpiryDate = hExpiryDateHis1.get(0).getCurrentactivelimitexpirydate();
				}
			}
			limitActiveProposal.setCurrentActiveLimitExpiryDate(currentActiveLimitExpiryDate);*/
		}
		for (DepositCalculation depositCalculation : depositCalculations) {
			depositCalculation.setSort(typeSort(depositCalculation.getLimitType()));
		}
		limitActiveProposals.sort(Comparator.comparingInt(LimitActiveProposal::getSort));
		depositCalculations.sort(Comparator.comparingInt(DepositCalculation::getSort));
		Long currentActiveLimit = null;
		Long currentActiveLimitNORMAL= null;
		if(limitActiveProposals!=null && limitActiveProposals.size()>0){
			for (LimitActiveProposal limitActiveProposal : limitActiveProposals) {
				if(limitActiveProposal.getLimitType().equals("TEMP")){
					currentActiveLimit = limitActiveProposal.getCurrentCreditLimit();
				}else if(limitActiveProposal.getLimitType().equals("NORMAL")){
					currentActiveLimitNORMAL = limitActiveProposal.getCurrentCreditLimit();
				}
			}
		}
		if(currentActiveLimit!= null && currentActiveLimitNORMAL!=null ){
			for (LimitActiveProposal limitActiveProposal : limitActiveProposals) {
				if(limitActiveProposal.getLimitType().equals("NORMAL")){
					limitActiveProposal.setCurrentCreditLimit2(currentActiveLimit+currentActiveLimitNORMAL);
				}else{
					limitActiveProposal.setCurrentCreditLimit2(limitActiveProposal.getCurrentCreditLimit());
				}
			}
		}else{
			for (LimitActiveProposal limitActiveProposal : limitActiveProposals) {
				limitActiveProposal.setCurrentCreditLimit2(limitActiveProposal.getCurrentCreditLimit());
			}
		}



		result.put("limitActiveProposals",limitActiveProposals);
		result.put("depositCalculations",depositCalculations);



		return result;
	}

	public Integer typeSort(String type){
		if(type.contains("/")){
			return 1;
		}
		String substring = type.substring(0, 1);
		if(substring.equalsIgnoreCase("N")){
			return 2;
		}
		if(substring.equalsIgnoreCase("D")){
			return 3;
		}
		if(substring.equalsIgnoreCase("T")){
			return 4;
		}
		if(substring.equalsIgnoreCase("C")){
			return 5;
		}
		if(substring.equalsIgnoreCase("M")){
			return 6;
		}
		return 7;
	}



	public Map<String, Object> getLimitActivationProposal2(DepositDecreaseDTO depositDecreaseDTO){
		int depositFlag =  1;

		DepositCalculation depositCalculationTemp = new DepositCalculation();
		depositCalculationTemp.setInstanceId(depositDecreaseDTO.getInstanceId());
		List<DepositCalculation> depositCalculationList = depositCalculationService.selectDepositCalculationList(depositCalculationTemp);
		String dealerCode = depositCalculationList.get(0).getDealerCode();
		List<String[]> strList = new ArrayList<String[]>();
		String[] str = new String[1];
		str[0] = dealerCode;
		strList.add(str);

		JSONObject jsonObject = new JSONObject();
		Map<String, Object> result = new HashMap<>();
		List<LimitActiveProposal> limitActiveProposals = new ArrayList<>();
		List<DepositCalculation> depositCalculations = new ArrayList<>();
		String[] dealerCodes = depositDecreaseDTO.getDealerCodeArr().get(0);
		//String dealerCode = dealerCodes[0];
		//String dealerCode = "K55105";
		DealerInformation dealerInformation = new DealerInformation();
		dealerInformation.setDealerCode(dealerCode);
		List<DealerInformation> dealerInformations = dealerInformationService.selectDealerInformationList2(dealerInformation);
		if (dealerInformations != null && dealerInformations.size() > 0) {
			dealerInformation = dealerInformations.get(0);
		}
		jsonObject.put("DealerCode", strList);
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost(wfsUrl + "CreditInfo");
		HttpPost httpPost2 = new HttpPost(wfsUrl + "SuspenseInfo");
		httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
		httpPost2.addHeader("Content-Type", "application/json;charset=UTF-8");
		StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
		entity.setContentType("application/json;charset=UTF-8");
		entity.setContentEncoding("UTF-8");
		httpPost.setEntity(entity);
		httpPost.setHeader("Accept", "application/json, text/plain, */*");
		httpPost.setHeader("Accept-Encoding", "gzip, deflate");
		httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38");
		httpPost2.setEntity(entity);
		httpPost2.setHeader("Accept", "application/json, text/plain, */*");
		httpPost2.setHeader("Accept-Encoding", "gzip, deflate");
		httpPost2.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
		httpPost2.setHeader("Connection", "keep-alive");
		httpPost2.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38");
		Map<String, Object> objectList = new HashMap<>();
		Map<String, Object> objectList2 = new HashMap<>();
		try {
			Map<String, Object> stringObjectHashMap = new HashMap<>();
			stringObjectHashMap.put("Deposit",0);
			stringObjectHashMap.put("CBDeposit",0);
			stringObjectHashMap.put("PartDeposit",0);
			stringObjectHashMap.put("UsedDeposit",0);
			HttpResponse response = httpClient.execute(httpPost);
			String responseStr = EntityUtils.toString(response.getEntity());
			HttpResponse response2 = httpClient.execute(httpPost2);
			String responseStr2 = EntityUtils.toString(response2.getEntity());
			log.info("WFS外部接口数据返回结果=[{}]", responseStr);
			log.info("WFS外部接口数据返回结果2=[{}]", responseStr2);
			objectList = JSONObject.parseObject(responseStr, Map.class);
			objectList2 = JSONObject.parseObject(responseStr2, Map.class);
			if (Integer.valueOf(String.valueOf(objectList.get("Code"))) == 200) {
				Map data = (Map) JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(objectList.get("Data"))).get(0))).get(0)), Map.class).get("CreditInfo"))).get(0);
				List creditDet = (List) data.get("CreditDet");
				try{
					stringObjectHashMap = JSONObject.parseObject(String.valueOf(JSONObject.parseObject(String.valueOf(JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(objectList2.get("Data"))).get(0))).get(0))).get("SuspenseInfo")), Map.class);
				}catch (Exception e){
					throw  new BaseException("WFS接口数据异常，请检查");
				}
				stringObjectHashMap.put("Deposit",stringObjectHashMap.get("Deposit") != null ? stringObjectHashMap.get("Deposit") : 0);
				stringObjectHashMap.put("CBDeposit",stringObjectHashMap.get("Deposit") != null ? stringObjectHashMap.get("CBDeposit") : 0);
				stringObjectHashMap.put("PartDeposit",stringObjectHashMap.get("PartDeposit") != null ? stringObjectHashMap.get("PartDeposit") : 0);
				stringObjectHashMap.put("UsedDeposit",stringObjectHashMap.get("UsedDeposit") != null ? stringObjectHashMap.get("UsedDeposit") : 0);
				List<Map<String, Object>> creditDets = creditDet;
				//是否存在NORMAL

				//NORMAL 数据
				BigDecimal zero = new BigDecimal(0);
				Map<String, Object> normalData = null;
				Boolean flag = true;
				for (int i = 0; i < creditDets.size(); i++) {
					Map<String, Object> objectMap = creditDets.get(i);
					if(objectMap.get("LimitType").toString().equalsIgnoreCase("NORMAL")){
						normalData = creditDets.get(i);
						break;
					}
				}

				for (int i = 0; i < creditDets.size(); i++) {
					Map<String, Object> objectMap = creditDets.get(i);
					LimitActiveProposal limitActiveProposal = new LimitActiveProposal();
					limitActiveProposal.setDealerName(dealerInformation.getDealerName());
					limitActiveProposal.setDealerCode(dealerCode);
					limitActiveProposal.setSector(dealerInformation.getMake());

					limitActiveProposal.setLimitType(String.valueOf(objectMap.get("LimitType")));
					limitActiveProposal.setCurrentCreditLimit(Long.valueOf(String.valueOf(objectMap.get("CreditLimit"))));

					//激活额度
					limitActiveProposal.setCurrentActiveLimit(String.valueOf(objectMap.get("ActiveLimit")));
					if(objectMap.get("LimitType").toString().equalsIgnoreCase("TEMP")){
						limitActiveProposal.setCurrentActiveLimit("");
					}


					//设置保证金比例
					if(objectMap.get("LimitType").toString().equalsIgnoreCase("CB")){
						limitActiveProposal.setApprovedCashDeposit(String.valueOf(objectMap.get("SecurityRatio")));
					}else if(objectMap.get("LimitType").toString().equalsIgnoreCase("TEMP") || objectMap.get("LimitType").toString().equalsIgnoreCase("MGR") ){
						//limitActiveProposal.setApprovedCashDeposit("");
					}else if(ObjectUtil.isNotEmpty(normalData) && (objectMap.get("LimitType").toString().equalsIgnoreCase("NORMAL") || objectMap.get("LimitType").toString().equalsIgnoreCase("DEMO") || objectMap.get("LimitType").toString().equalsIgnoreCase("USED"))){
						limitActiveProposal.setApprovedCashDeposit(String.valueOf(normalData.get("SecurityRatio")));
					}


					limitActiveProposal.setOs(String.valueOf(objectMap.get("ActiveOS")));
					if(!StringUtils.isEmpty(String.valueOf(objectMap.get("ActiveExpireDate")))){
						String activeExpireDate = String.valueOf(objectMap.get("ActiveExpireDate"));
						String replace = activeExpireDate.replace("/", "-");
						limitActiveProposal.setCurrentActiveLimitExpiryDate(replace);
					}else{
						limitActiveProposal.setCurrentActiveLimitExpiryDate(null);
					}

					if (objectMap.get("LimitType").equals("NORMAL") || objectMap.get("LimitType").equals("DEMO")) {
						limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("Deposit")));

					} else if (objectMap.get("LimitType").equals("CB")) {
						limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("CBDeposit")));
					} else if (objectMap.get("LimitType").equals("PART")){
						limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("PartDeposit")));
					}else if (objectMap.get("LimitType").equals("USED")){
						limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("UsedDeposit")));
					}
					if (StringUtils.isNotEmpty(limitActiveProposal.getApprovedCashDeposit())) {
						if(StringUtils.isNotEmpty(limitActiveProposal.getApprovedCashDeposit()) && StringUtils.isNotEmpty(limitActiveProposal.getProposalCashDeposit())){
							//Double aDouble = Double.valueOf(limitActiveProposal.getApprovedCashDeposit().replace("%", ""));
							String replace = limitActiveProposal.getApprovedCashDeposit().replace("%", "");
							BigDecimal bigDecimal2 = new BigDecimal(limitActiveProposal.getProposalCashDeposit());
							BigDecimal bigDecimal3 = new BigDecimal(replace).setScale(4, BigDecimal.ROUND_CEILING);
							BigDecimal bigDecimal4 = bigDecimal2.divide(bigDecimal3,4,BigDecimal.ROUND_HALF_UP);
							BigDecimal bigDecimal5 = bigDecimal4.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
							//BigDecimal bigDecimal = new BigDecimal(limitActiveProposal.getProposalCashDeposit()).divide(new BigDecimal(aDouble)).setScale(2, BigDecimal.ROUND_HALF_UP);
							//BigDecimal bigDecimal1 = bigDecimal.divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);


							limitActiveProposal.setLimitCoveredDeposit(bigDecimal5.toString());
						}
					} else {
						limitActiveProposal.setLimitCoveredDeposit("");
					}
					limitActiveProposal.setProposedStart(new Date());
					if(objectMap.get("LimitType").toString().equals("TEMP")){
						//手动输入
						limitActiveProposal.setProposedEnd(null);
						limitActiveProposal.setProposedExpiredDate(null);
					}else if (objectMap.get("LimitType").toString().equals("PART") && ObjectUtil.isNotEmpty(normalData)){
						if(StringUtils.isNotEmpty(normalData) &&  normalData.get("ExpiryDate")!=null) {
							limitActiveProposal.setProposedEnd(new Date(String.valueOf(normalData.get("ExpiryDate"))));
							limitActiveProposal.setProposedExpiredDate(new Date(String.valueOf(normalData.get("ExpiryDate"))));
						}
					}else if ((objectMap.get("LimitType").toString().equals("DEMO") ||  objectMap.get("LimitType").toString().equals("CB")) && ObjectUtil.isNotEmpty(normalData)){
						if(StringUtils.isNotEmpty(normalData) &&  normalData.get("ExpiryDate")!=null) {
							limitActiveProposal.setProposedEnd(new Date(String.valueOf(normalData.get("ExpiryDate"))));
							limitActiveProposal.setProposedExpiredDate(new Date(String.valueOf(normalData.get("ExpiryDate"))));
						}
					}
					else if (StringUtils.isNotEmpty(String.valueOf(objectMap.get("ExpiryDate")))){
						limitActiveProposal.setProposedEnd(new Date(String.valueOf(objectMap.get("ExpiryDate"))));
						limitActiveProposal.setProposedExpiredDate(new Date(String.valueOf(objectMap.get("ExpiryDate"))));
					}
					DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
					dealercodeContractFiling.setDealerNameCN(dealerInformation.getDealerName());
					dealercodeContractFiling.setSector(dealerInformation.getMake());
					dealercodeContractFiling.setLimitType(String.valueOf(objectMap.get("LimitType")));
					List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingListRecentlyEffectiveDate(dealercodeContractFiling);
					if(StringUtils.isNotEmpty(dealercodeContractFilings)){
						Date parse = null;
						if(StringUtils.isNotEmpty(dealercodeContractFilings.get(0).getFacilityAmount())) {
							limitActiveProposal.setContractFacilityAmount(dealercodeContractFilings.get(0).getFacilityAmount());
						}
						if(StringUtils.isNotEmpty(dealercodeContractFilings.get(0).getExpiredDate())) {
							try {
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
								parse = sdf.parse(dealercodeContractFilings.get(0).getExpiredDate());
							} catch (Exception e) {
								e.printStackTrace();
								new BaseException("日期转化异常");
							}
							limitActiveProposal.setContractExpireDate(parse);
						}
						if(StringUtils.isNotEmpty(dealercodeContractFilings.get(0).getDeposit())) {
							limitActiveProposal.setContractDepositRatio(dealercodeContractFilings.get(0).getDeposit());
						}
						if(StringUtils.isNotEmpty(dealercodeContractFilings.get(0).getContractLocation())){
							limitActiveProposal.setContractHyperlink(dealercodeContractFilings.get(0).getContractLocation());
						}
					}
					DepositCalculation depositCalculation = new DepositCalculation();
					depositCalculation.setDealerName(limitActiveProposal.getDealerName());
					depositCalculation.setDealerCode(limitActiveProposal.getDealerCode());
					depositCalculation.setSector(limitActiveProposal.getSector());
					depositCalculation.setLimitType(limitActiveProposal.getLimitType());
					depositCalculation.setCurrentAmount(String.valueOf(limitActiveProposal.getProposalCashDeposit()));
					// depositCalculation.setProposedAmount(String.valueOf(Long.valueOf(limitActiveProposal.getProposalActiveLimit()) * Double.valueOf(limitActiveProposal.getApprovedCashDeposit().replace("%", ""))));
					// depositCalculation.setGap(String.valueOf(Double.valueOf(depositCalculation.getProposedAmount()) - Double.valueOf(depositCalculation.getCurrentAmount())));
					depositCalculations.add(depositCalculation);
					limitActiveProposals.add(limitActiveProposal);
				}
			}
			log.info("WFS外部接口数据返回JSON结果=[{}]", JSON.toJSONString(responseStr));

		} catch (IOException e) {
			e.printStackTrace();
		}

		List<DepositCalculation> calculations = new ArrayList<>();
		System.out.println("depositCalculations第一次"+depositCalculations);
		for (DepositCalculation depositCalculation : depositCalculations) {
			if(depositCalculation.getLimitType().equals("NORMAL") || depositCalculation.getLimitType().equals("DEMO") || depositCalculation.getLimitType().equals("TEMP")){
				calculations.add(depositCalculation);
			}
		}
		System.out.println("calculations"+calculations);
		if(calculations.size() >= 2){
			Iterator<DepositCalculation> iterator = depositCalculations.iterator();

			while(iterator.hasNext()) {
				DepositCalculation next = iterator.next();

				if (next.getLimitType().equals("NORMAL") || next.getLimitType().equals("DEMO") || next.getLimitType().equals("TEMP")) {
					iterator.remove();
				}
			}

			DepositCalculation depositCalculation = calculations.get(0);
			depositCalculation.setLimitType("NORMAL/DEMO/TEMP");
			depositCalculations.add(depositCalculation);

		}
		System.out.println("depositCalculations第二次"+depositCalculations);
		List<DepositCalculation> depositCalculations2 = new ArrayList<>();

		for (DepositCalculation deposit : depositCalculations) {
			for (DepositCalculation calculation : depositCalculationList) {
				if(deposit.getDealerName().equals(calculation.getDealerName()) && deposit.getLimitType().equals(calculation.getLimitType())
						&& deposit.getSector().equals(calculation.getSector())){
					if(deposit.getCurrentAmount()==null ||  deposit.getCurrentAmount().equals("null") ){
						calculation.setCurrentAmount(null);
					}else{
						calculation.setCurrentAmount(deposit.getCurrentAmount());
					}
					if(!StringUtils.isEmpty(calculation.getProposedAmount()) && !StringUtils.isEmpty(deposit.getCurrentAmount()) ){
						BigDecimal bigDecimal = new BigDecimal(calculation.getProposedAmount());
						BigDecimal bigDecimal2 = new BigDecimal(deposit.getCurrentAmount());
						BigDecimal subtract = bigDecimal.subtract(bigDecimal2);
						calculation.setGap(subtract.toString());
					}
					depositCalculations2.add(calculation);
					calculation.setNewAmount(calculation.getCurrentAmount());
					depositCalculationService.updateDepositCalculationByDeposit(calculation);
				}
			}
		}
		System.out.println("depositCalculations22222222"+depositCalculations2);
		List<DepositCalculation> depositCalculations3 = new ArrayList<>();
		int i = 1;
		for (DepositCalculation depositCalculation : depositCalculations2) {
			//增加数据
			System.out.println("000000001");
			if (StringUtils.isNotEmpty(depositCalculation.getTransferTo()) && StringUtils.isNotEmpty(depositCalculation.getTransfertolimittype())) {
				System.out.println("00000000");
				depositCalculation.setOldCurrentAmount(depositCalculation.getOldAmount());
				depositCalculation.setSort(i);
				i++;
				depositCalculations3.add(depositCalculation);
				try{
					String[] split = depositCalculation.getTransferTo().split("-");
					String DealerCode = split[0];
					String[] str1 = new String[1];
					str1[0] = DealerCode;
					ArrayList<String[]> DealerCodes = new ArrayList<>();
					DealerCodes.add(str1);
					DepositDecreaseDTO depositDecreaseDTO2 = new DepositDecreaseDTO();
					depositDecreaseDTO2.setDealerCodeArr(DealerCodes);
					AjaxResult deposit = getDeposit(depositDecreaseDTO2);
					if(deposit.get("code").toString().equals("200")){
						Object data = deposit.get("data");
						List<Map<String, Object>> CreditLimitMap = (List<Map<String, Object>>) data;
						for (Map<String, Object> stringObjectMap : CreditLimitMap) {
							//查询
							//查询品牌
							DealerInformation dealerInformationSelect = new DealerInformation();
							dealerInformationSelect.setDealerCode(split[0]);
							dealerInformationSelect.setDealerName(split[1]);
							List<DealerInformation> dealerInformations1 = dealerInformationService.selectDealerInformationList2(dealerInformationSelect);
							String Sector ="";
							if(dealerInformations1!=null && dealerInformations1.get(0).getMake()!=null){
								Sector = dealerInformations1.get(0).getMake();
							}
							if(depositCalculation.getTransfertolimittype().equals("NORMAL")){
								Object Deposit = stringObjectMap.get("Deposit");
								//这里要new
								DepositCalculation depositCalculationAdd = new DepositCalculation();
								depositCalculationAdd.setDealerName(split[1]);
								depositCalculationAdd.setDealerCode(split[0]);
								depositCalculationAdd.setLimitType(depositCalculation.getTransfertolimittype());
								depositCalculationAdd.setOldCurrentAmount(depositCalculation.getTransferOldAmount());
								depositCalculationAdd.setSector(Sector);
								depositCalculationAdd.setDealerId("temp");
								depositCalculationAdd.setCurrentAmount(Deposit.toString());
								depositCalculationAdd.setTransferAmount(depositCalculation.getTransferAmount());
								depositCalculationAdd.setSort(i);
								i++;
								depositCalculations3.add(depositCalculationAdd);
								depositCalculation.setTransferNewAmount(Deposit.toString());
								//查询后update
								depositCalculationService.updateDepositCalculationByDeposit(depositCalculation);
							}else if (depositCalculation.getTransfertolimittype().equals("CB")){
								Object cbDeposit = stringObjectMap.get("CBDeposit");
								//这里要new
								DepositCalculation depositCalculationAdd = new DepositCalculation();
								depositCalculationAdd.setDealerName(split[1]);
								depositCalculationAdd.setDealerCode(split[0]);
								depositCalculationAdd.setLimitType(depositCalculation.getTransfertolimittype());
								depositCalculationAdd.setOldCurrentAmount(depositCalculation.getTransferOldAmount());
								depositCalculationAdd.setSector(Sector);
								depositCalculationAdd.setDealerId("temp");
								depositCalculationAdd.setCurrentAmount(cbDeposit.toString());
								depositCalculationAdd.setTransferAmount(depositCalculation.getTransferAmount());
								depositCalculationAdd.setSort(i);
								i++;
								depositCalculations3.add(depositCalculationAdd);
								depositCalculation.setTransferNewAmount(cbDeposit.toString());
								//查询后update
								depositCalculationService.updateDepositCalculationByDeposit(depositCalculation);
							}else if (depositCalculation.getTransfertolimittype().equals("PART")){
								Object partDeposit = stringObjectMap.get("PartDeposit");
								//这里要new
								DepositCalculation depositCalculationAdd = new DepositCalculation();
								depositCalculationAdd.setDealerName(split[1]);
								depositCalculationAdd.setDealerCode(split[0]);
								depositCalculationAdd.setLimitType(depositCalculation.getTransfertolimittype());
								depositCalculationAdd.setOldCurrentAmount(depositCalculation.getTransferOldAmount());
								depositCalculationAdd.setSector(Sector);
								depositCalculationAdd.setDealerId("temp");
								depositCalculationAdd.setCurrentAmount(partDeposit.toString());
								depositCalculationAdd.setTransferAmount(depositCalculation.getTransferAmount());
								depositCalculationAdd.setSort(i);
								i++;
								depositCalculations3.add(depositCalculationAdd);
								depositCalculation.setTransferNewAmount(partDeposit.toString());
								//查询后update
								depositCalculationService.updateDepositCalculationByDeposit(depositCalculation);
							}else if (depositCalculation.getTransfertolimittype().equals("USED")){
								Object usedDeposit = stringObjectMap.get("UsedDeposit");
								//这里要new
								DepositCalculation depositCalculationAdd = new DepositCalculation();
								depositCalculationAdd.setDealerName(split[1]);
								depositCalculationAdd.setDealerCode(split[0]);
								depositCalculationAdd.setLimitType(depositCalculation.getTransfertolimittype());
								depositCalculationAdd.setOldCurrentAmount(depositCalculation.getTransferOldAmount());
								depositCalculationAdd.setSector(Sector);
								depositCalculationAdd.setDealerId("temp");
								depositCalculationAdd.setCurrentAmount(usedDeposit.toString());
								depositCalculationAdd.setTransferAmount(depositCalculation.getTransferAmount());
								depositCalculationAdd.setSort(i);
								i++;
								depositCalculations3.add(depositCalculationAdd);
								depositCalculation.setTransferNewAmount(usedDeposit.toString());
								//查询后update
								depositCalculationService.updateDepositCalculationByDeposit(depositCalculation);
							}
						}

					}
				}catch (Exception e){
					e.printStackTrace();
					new BaseException("查询WFS保证金数据异常,请联系管理员");
				}

			}else{
				if(depositDecreaseDTO.getFlag().equals("2")){
					if(StringUtils.isNotEmpty(depositCalculation.getGap() ) && !depositCalculation.getGap().equals("0.00") && !depositCalculation.getProcess().equals("Keep")){
						depositCalculation.setOldCurrentAmount(depositCalculation.getOldAmount());
						depositCalculation.setSort(i);
						i++;
						depositCalculations3.add(depositCalculation);
					}else if(depositCalculation.getLimitType().equals("NORMAL/DEMO/TEMP")){
						depositCalculation.setOldCurrentAmount(depositCalculation.getOldAmount());
						depositCalculation.setSort(i);
						i++;
						depositCalculations3.add(depositCalculation);
					}else if (StringUtils.isNotEmpty(depositCalculation.getProcess()) && !depositCalculation.getProcess().equals("Keep")){
						depositCalculation.setOldCurrentAmount(depositCalculation.getOldAmount());
						depositCalculation.setSort(i);
						i++;
						depositCalculations3.add(depositCalculation);
					}
				}else{
						depositCalculation.setOldCurrentAmount(depositCalculation.getOldAmount());
						depositCalculation.setSort(i);
						i++;
						depositCalculations3.add(depositCalculation);
				}
			}

		}
		System.out.println("depositCalculations3"+depositCalculations3);
		if(depositDecreaseDTO.getFlag().equals("2")){
			depositFlag = 2;

			for (DepositCalculation depositCalculation : depositCalculations3) {
				if(StringUtils.isNotEmpty(depositCalculation.getDealerId())){
					String transferAmount ="0";
					String currentAmount = "0";
					String transferCurrentAmount = "0";
					if(StringUtils.isNotEmpty(depositCalculation.getTransferAmount())){
						  transferAmount = depositCalculation.getTransferAmount().replace(",","");
					}
					if(StringUtils.isNotEmpty(depositCalculation.getCurrentAmount())){
						 currentAmount = depositCalculation.getCurrentAmount().replace(",","");
					}
					if(StringUtils.isNotEmpty(depositCalculation.getOldCurrentAmount())){
						transferCurrentAmount = depositCalculation.getOldCurrentAmount().replace(",","");
					}
					BigDecimal check = new BigDecimal(transferCurrentAmount).add(new BigDecimal(transferAmount));
					if(check.compareTo(new BigDecimal(currentAmount)) == 0){
						depositCalculation.setCheckFlag(1);
					}else{
						depositCalculation.setCheckFlag(0);
					}
				}else{
					String transferAmount ="0";
					String currentAmount = "0";
					String transferCurrentAmount = "0";

					if(StringUtils.isNotEmpty(depositCalculation.getTransferAmount())){
						transferAmount = depositCalculation.getTransferAmount().replace(",","");
					}
					if(StringUtils.isNotEmpty(depositCalculation.getCurrentAmount())){
						currentAmount = depositCalculation.getCurrentAmount().replace(",","");
					}
					if(StringUtils.isNotEmpty(depositCalculation.getOldAmount())){
						transferCurrentAmount = depositCalculation.getOldAmount().replace(",","");
					}
					BigDecimal check = new BigDecimal(currentAmount).add(new BigDecimal(transferAmount));
					if(check.compareTo(new BigDecimal(transferCurrentAmount)) == 0){
						depositCalculation.setCheckFlag(1);
					}else{
						depositCalculation.setCheckFlag(0);
					}


				}
			}
		}
		depositCalculations3.sort(Comparator.comparingInt(DepositCalculation::getSort));

		result.put("depositCalculations",depositCalculations3);

		result.put("depositFlag",depositFlag);
		return result;
	}





	public Map<String, Object> getLimitActivationProposal4(DepositDecreaseDTO depositDecreaseDTO){

		DepositCalculation depositCalculationTemp = new DepositCalculation();
		depositCalculationTemp.setInstanceId(depositDecreaseDTO.getInstanceId());
		List<DepositCalculation> depositCalculationList = depositCalculationService.selectDepositCalculationList(depositCalculationTemp);
		String dealerCode = depositCalculationList.get(0).getDealerCode();
		List<String[]> strList = new ArrayList<String[]>();
		String[] str = new String[1];
		str[0] = dealerCode;
		strList.add(str);

		JSONObject jsonObject = new JSONObject();
		Map<String, Object> result = new HashMap<>();
		List<LimitActiveProposal> limitActiveProposals = new ArrayList<>();
		List<DepositCalculation> depositCalculations = new ArrayList<>();
		String[] dealerCodes = depositDecreaseDTO.getDealerCodeArr().get(0);
		//String dealerCode = dealerCodes[0];
		//String dealerCode = "K55105";
		DealerInformation dealerInformation = new DealerInformation();
		dealerInformation.setDealerCode(dealerCode);
		List<DealerInformation> dealerInformations = dealerInformationService.selectDealerInformationList2(dealerInformation);
		if (dealerInformations != null && dealerInformations.size() > 0) {
			dealerInformation = dealerInformations.get(0);
		}
		jsonObject.put("DealerCode", strList);
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost(wfsUrl + "CreditInfo");
		HttpPost httpPost2 = new HttpPost(wfsUrl + "SuspenseInfo");
		httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
		httpPost2.addHeader("Content-Type", "application/json;charset=UTF-8");
		StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
		entity.setContentType("application/json;charset=UTF-8");
		entity.setContentEncoding("UTF-8");
		httpPost.setEntity(entity);
		httpPost.setHeader("Accept", "application/json, text/plain, */*");
		httpPost.setHeader("Accept-Encoding", "gzip, deflate");
		httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38");
		httpPost2.setEntity(entity);
		httpPost2.setHeader("Accept", "application/json, text/plain, */*");
		httpPost2.setHeader("Accept-Encoding", "gzip, deflate");
		httpPost2.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
		httpPost2.setHeader("Connection", "keep-alive");
		httpPost2.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38");
		Map<String, Object> objectList = new HashMap<>();
		Map<String, Object> objectList2 = new HashMap<>();
		try {
			Map<String, Object> stringObjectHashMap = new HashMap<>();
			stringObjectHashMap.put("Deposit",0);
			stringObjectHashMap.put("CBDeposit",0);
			stringObjectHashMap.put("PartDeposit",0);
			stringObjectHashMap.put("UsedDeposit",0);
			HttpResponse response = httpClient.execute(httpPost);
			String responseStr = EntityUtils.toString(response.getEntity());
			HttpResponse response2 = httpClient.execute(httpPost2);
			String responseStr2 = EntityUtils.toString(response2.getEntity());
			log.info("WFS外部接口数据返回结果=[{}]", responseStr);
			log.info("WFS外部接口数据返回结果2=[{}]", responseStr2);
			objectList = JSONObject.parseObject(responseStr, Map.class);
			objectList2 = JSONObject.parseObject(responseStr2, Map.class);
			if (Integer.valueOf(String.valueOf(objectList.get("Code"))) == 200) {
				Map data = (Map) JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(objectList.get("Data"))).get(0))).get(0)), Map.class).get("CreditInfo"))).get(0);
				List creditDet = (List) data.get("CreditDet");
				try{
					stringObjectHashMap = JSONObject.parseObject(String.valueOf(JSONObject.parseObject(String.valueOf(JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(objectList2.get("Data"))).get(0))).get(0))).get("SuspenseInfo")), Map.class);
				}catch (NullPointerException e){

				}
				stringObjectHashMap.put("Deposit",stringObjectHashMap.get("Deposit") != null ? stringObjectHashMap.get("Deposit") : 0);
				stringObjectHashMap.put("CBDeposit",stringObjectHashMap.get("Deposit") != null ? stringObjectHashMap.get("CBDeposit") : 0);
				stringObjectHashMap.put("PartDeposit",stringObjectHashMap.get("PartDeposit") != null ? stringObjectHashMap.get("PartDeposit") : 0);
				stringObjectHashMap.put("UsedDeposit",stringObjectHashMap.get("UsedDeposit") != null ? stringObjectHashMap.get("UsedDeposit") : 0);
				List<Map<String, Object>> creditDets = creditDet;
				//是否存在NORMAL

				//NORMAL 数据
				BigDecimal zero = new BigDecimal(0);
				Map<String, Object> normalData = null;
				Boolean flag = true;
				for (int i = 0; i < creditDets.size(); i++) {
					Map<String, Object> objectMap = creditDets.get(i);
					if(objectMap.get("LimitType").toString().equalsIgnoreCase("NORMAL")){
						normalData = creditDets.get(i);
						break;
					}
				}

				for (int i = 0; i < creditDets.size(); i++) {
					Map<String, Object> objectMap = creditDets.get(i);
					LimitActiveProposal limitActiveProposal = new LimitActiveProposal();
					limitActiveProposal.setDealerName(dealerInformation.getDealerName());
					limitActiveProposal.setDealerCode(dealerCode);
					limitActiveProposal.setSector(dealerInformation.getMake());

					limitActiveProposal.setLimitType(String.valueOf(objectMap.get("LimitType")));
					limitActiveProposal.setCurrentCreditLimit(Long.valueOf(String.valueOf(objectMap.get("CreditLimit"))));

					//激活额度
					limitActiveProposal.setCurrentActiveLimit(String.valueOf(objectMap.get("ActiveLimit")));
					if(objectMap.get("LimitType").toString().equalsIgnoreCase("TEMP")){
						limitActiveProposal.setCurrentActiveLimit("");
					}


					//设置保证金比例
					if(objectMap.get("LimitType").toString().equalsIgnoreCase("CB")){
						limitActiveProposal.setApprovedCashDeposit(String.valueOf(objectMap.get("SecurityRatio")));
					}else if(objectMap.get("LimitType").toString().equalsIgnoreCase("TEMP") || objectMap.get("LimitType").toString().equalsIgnoreCase("MGR") ){
						//limitActiveProposal.setApprovedCashDeposit("");
					}else if(ObjectUtil.isNotEmpty(normalData) && (objectMap.get("LimitType").toString().equalsIgnoreCase("NORMAL") || objectMap.get("LimitType").toString().equalsIgnoreCase("DEMO") || objectMap.get("LimitType").toString().equalsIgnoreCase("USED"))){
						limitActiveProposal.setApprovedCashDeposit(String.valueOf(normalData.get("SecurityRatio")));
					}


					limitActiveProposal.setOs(String.valueOf(objectMap.get("ActiveOS")));
					if(!StringUtils.isEmpty(String.valueOf(objectMap.get("ActiveExpireDate")))){
						String activeExpireDate = String.valueOf(objectMap.get("ActiveExpireDate"));
						String replace = activeExpireDate.replace("/", "-");
						limitActiveProposal.setCurrentActiveLimitExpiryDate(replace);
					}else{
						limitActiveProposal.setCurrentActiveLimitExpiryDate(null);
					}

					if (objectMap.get("LimitType").equals("NORMAL") || objectMap.get("LimitType").equals("DEMO")) {
						limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("Deposit")));

					} else if (objectMap.get("LimitType").equals("CB")) {
						limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("CBDeposit")));
					}else if (objectMap.get("LimitType").equals("PART")){
						limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("PartDeposit")));
					}else if (objectMap.get("LimitType").equals("USED")){
						limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("UsedDeposit")));
					}
					if (StringUtils.isNotEmpty(limitActiveProposal.getApprovedCashDeposit())) {
						if(StringUtils.isNotEmpty(limitActiveProposal.getApprovedCashDeposit()) && StringUtils.isNotEmpty(limitActiveProposal.getProposalCashDeposit())){
							//Double aDouble = Double.valueOf(limitActiveProposal.getApprovedCashDeposit().replace("%", ""));
							String replace = limitActiveProposal.getApprovedCashDeposit().replace("%", "");
							BigDecimal bigDecimal2 = new BigDecimal(limitActiveProposal.getProposalCashDeposit());
							BigDecimal bigDecimal3 = new BigDecimal(replace).setScale(4, BigDecimal.ROUND_CEILING);
							BigDecimal bigDecimal4 = bigDecimal2.divide(bigDecimal3,4,BigDecimal.ROUND_HALF_UP);
							BigDecimal bigDecimal5 = bigDecimal4.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
							//BigDecimal bigDecimal = new BigDecimal(limitActiveProposal.getProposalCashDeposit()).divide(new BigDecimal(aDouble)).setScale(2, BigDecimal.ROUND_HALF_UP);
							//BigDecimal bigDecimal1 = bigDecimal.divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);


							limitActiveProposal.setLimitCoveredDeposit(bigDecimal5.toString());
						}
					} else {
						limitActiveProposal.setLimitCoveredDeposit("");
					}
					limitActiveProposal.setProposedStart(new Date());
					if(objectMap.get("LimitType").toString().equals("TEMP")){
						//手动输入
						limitActiveProposal.setProposedEnd(null);
						limitActiveProposal.setProposedExpiredDate(null);
					}else if ((objectMap.get("LimitType").toString().equals("DEMO") ||  objectMap.get("LimitType").toString().equals("CB")) && ObjectUtil.isNotEmpty(normalData)){
						if(StringUtils.isNotEmpty(normalData) &&  normalData.get("ExpiryDate")!=null) {
							limitActiveProposal.setProposedEnd(new Date(String.valueOf(normalData.get("ExpiryDate"))));
							limitActiveProposal.setProposedExpiredDate(new Date(String.valueOf(normalData.get("ExpiryDate"))));
						}
					}else if (objectMap.get("LimitType").toString().equals("PART") && ObjectUtil.isNotEmpty(normalData)){
						if(StringUtils.isNotEmpty(normalData) &&  normalData.get("ExpiryDate")!=null) {
							limitActiveProposal.setProposedEnd(new Date(String.valueOf(normalData.get("ExpiryDate"))));
							limitActiveProposal.setProposedExpiredDate(new Date(String.valueOf(normalData.get("ExpiryDate"))));
						}
					}else if (StringUtils.isNotEmpty(String.valueOf(objectMap.get("ExpiryDate")))){
						limitActiveProposal.setProposedEnd(new Date(String.valueOf(objectMap.get("ExpiryDate"))));
						limitActiveProposal.setProposedExpiredDate(new Date(String.valueOf(objectMap.get("ExpiryDate"))));
					}
					DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
					dealercodeContractFiling.setDealerNameCN(dealerInformation.getDealerName());
					dealercodeContractFiling.setSector(dealerInformation.getMake());
					dealercodeContractFiling.setLimitType(String.valueOf(objectMap.get("LimitType")));
					List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingListRecentlyEffectiveDate(dealercodeContractFiling);
					if(StringUtils.isNotEmpty(dealercodeContractFilings)){
						Date parse = null;
						if(StringUtils.isNotEmpty(dealercodeContractFilings.get(0).getFacilityAmount())) {
							limitActiveProposal.setContractFacilityAmount(dealercodeContractFilings.get(0).getFacilityAmount());
						}
						if(StringUtils.isNotEmpty(dealercodeContractFilings.get(0).getExpiredDate())) {
							try {
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
								parse = sdf.parse(dealercodeContractFilings.get(0).getExpiredDate());
							} catch (Exception e) {
								e.printStackTrace();
								new BaseException("日期转化异常");
							}
							limitActiveProposal.setContractExpireDate(parse);
						}
						if(StringUtils.isNotEmpty(dealercodeContractFilings.get(0).getDeposit())) {
							limitActiveProposal.setContractDepositRatio(dealercodeContractFilings.get(0).getDeposit());
						}
						if(StringUtils.isNotEmpty(dealercodeContractFilings.get(0).getContractLocation())){
							limitActiveProposal.setContractHyperlink(dealercodeContractFilings.get(0).getContractLocation());
						}
					}
					DepositCalculation depositCalculation = new DepositCalculation();
					depositCalculation.setDealerName(limitActiveProposal.getDealerName());
					depositCalculation.setDealerCode(limitActiveProposal.getDealerCode());
					depositCalculation.setSector(limitActiveProposal.getSector());
					depositCalculation.setLimitType(limitActiveProposal.getLimitType());
					depositCalculation.setCurrentAmount(String.valueOf(limitActiveProposal.getProposalCashDeposit()));
					// depositCalculation.setProposedAmount(String.valueOf(Long.valueOf(limitActiveProposal.getProposalActiveLimit()) * Double.valueOf(limitActiveProposal.getApprovedCashDeposit().replace("%", ""))));
					// depositCalculation.setGap(String.valueOf(Double.valueOf(depositCalculation.getProposedAmount()) - Double.valueOf(depositCalculation.getCurrentAmount())));
					depositCalculations.add(depositCalculation);
					limitActiveProposals.add(limitActiveProposal);
				}
			}
			log.info("WFS外部接口数据返回JSON结果=[{}]", JSON.toJSONString(responseStr));

		} catch (IOException e) {
			e.printStackTrace();
		}



		List<DepositCalculation> calculations = new ArrayList<>();

		for (DepositCalculation depositCalculation : depositCalculations) {
			if(depositCalculation.getLimitType().equals("NORMAL") || depositCalculation.getLimitType().equals("DEMO")  || depositCalculation.getLimitType().equals("TEMP")){
				calculations.add(depositCalculation);
			}
		}

		if(calculations.size() >= 2){
			Iterator<DepositCalculation> iterator = depositCalculations.iterator();

			while(iterator.hasNext()) {
				DepositCalculation next = iterator.next();

				if (next.getLimitType().equals("NORMAL") || next.getLimitType().equals("DEMO") || next.getLimitType().equals("TEMP")) {
					iterator.remove();
				}
			}

			DepositCalculation depositCalculation = calculations.get(0);
			depositCalculation.setLimitType("NORMAL/DEMO/TEMP");
			depositCalculations.add(depositCalculation);

		}
		List<HLimitSetupResult> hLimitSetupResults = new ArrayList<>();
		for (LimitActiveProposal limitActiveProposal : limitActiveProposals) {
			limitActiveProposal.setSort(typeSort(limitActiveProposal.getLimitType()));
			HLimitSetupResult hLimitSetupResult = new HLimitSetupResult();
			hLimitSetupResult.setDealername(limitActiveProposal.getDealerName());
			hLimitSetupResult.setSector(limitActiveProposal.getSector());
			hLimitSetupResult.setLimittype(limitActiveProposal.getLimitType());
			hLimitSetupResult.setCurrentactivelimit(limitActiveProposal.getCurrentActiveLimit());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				if(limitActiveProposal.getCurrentActiveLimitExpiryDate()!=null){
					Date parse = sdf.parse(limitActiveProposal.getCurrentActiveLimitExpiryDate());
					hLimitSetupResult.setCurrentactivelimitexpirydate(parse);
				}
			}catch (Exception e){
				e.printStackTrace();
			}
			hLimitSetupResult.setOs(limitActiveProposal.getOs());
			hLimitSetupResult.setSort(typeSort(limitActiveProposal.getLimitType()));
			hLimitSetupResults.add(hLimitSetupResult);
		}
		hLimitSetupResults.sort(Comparator.comparingInt(HLimitSetupResult::getSort));
		result.put("limitSetupResult",hLimitSetupResults);

		//先删后插
		HLimitSetupResult hLimitSetupResult = new HLimitSetupResult();
		hLimitSetupResult.setInstanceid(depositDecreaseDTO.getInstanceId());
		List<HLimitSetupResult> hLimitSetupResultsUpdate = limitSetupResultService.selectHLimitSetupResultList(hLimitSetupResult);
		for (HLimitSetupResult limitSetupResult : hLimitSetupResultsUpdate) {
			limitSetupResultService.deleteHLimitSetupResultById(limitSetupResult.getId());
		}
		for (HLimitSetupResult limitSetupResult : hLimitSetupResults) {
			limitSetupResult.setInstanceid(depositDecreaseDTO.getInstanceId());
			limitSetupResultService.insertHLimitSetupResult(limitSetupResult);
		}

		return result;
	}



	@ApiOperation("查询WfsLimitSetUp流程")
	@Log(title = "feike")
	@GetMapping(value = "/{instanceId}")
	public AjaxResult getInfo(@PathVariable("instanceId") String instanceId) {
		return AjaxResult.success(wfsLimitSetUpService.selectWfsLimitSetUpdto(instanceId));
	}

	@ApiOperation("Deposit Calculation")
	@PostMapping("/depositCalculation")
	public AjaxResult depositCalculation(@RequestBody List<LimitActiveProposal> limitActiveProposals) {
		List<DepositCalculation> depositCalculations = new ArrayList<>();
		try {
			for (int i = 0; i < limitActiveProposals.size(); i++) {
				LimitActiveProposal limitActiveProposal = limitActiveProposals.get(i);
				DepositCalculation depositCalculation = new DepositCalculation();
				depositCalculation.setDealerName(limitActiveProposal.getDealerName());
				depositCalculation.setDealerCode(limitActiveProposal.getDealerCode());
				depositCalculation.setSector(limitActiveProposal.getSector());
				depositCalculation.setCurrentAmount(String.valueOf(limitActiveProposal.getProposalCashDeposit()));
				depositCalculation.setProposedAmount(String.valueOf(Long.valueOf(limitActiveProposal.getProposalActiveLimit()) * Double.valueOf(limitActiveProposal.getApprovedCashDeposit().replace("%", ""))));
				depositCalculation.setGap(String.valueOf(Double.valueOf(depositCalculation.getProposedAmount()) - Double.valueOf(depositCalculation.getCurrentAmount())));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return AjaxResult.success(depositCalculations);
	}

	@ApiOperation("New Sum Select")
	@PostMapping("/newSumSelect")
	public AjaxResult newSum(@RequestBody NewSumKeep newSumKeep) {
		return AjaxResult.success(newSumKeepService.newSumSelect(newSumKeep));
	}

	@ApiOperation("updateNewSum")
	@PostMapping("/updateNewSum")
	public AjaxResult updateNewSum(@RequestBody NewSumKeep newSumKeep) {
		WfsLimitSetUpdto wfsLimitSetUpdto = new WfsLimitSetUpdto();
		//拿到开始日期和结束日期
		Date newEffectiveDate = newSumKeep.getEffectiveDate();
		Date expiryDate = newSumKeep.getExpiryDate();
		if(newEffectiveDate.getTime()>expiryDate.getTime()){
			throw  new BaseException("起始日不能大于到期日");
			/*NewSum newSum = new NewSum();
			newSum.setInstanceId(newSumKeep.getInstanceId());
			List<NewSum> newSumList = newSumService.selectNewSumList(newSum);
			InsuranceCalculation insuranceCalculation = new InsuranceCalculation();
			insuranceCalculation.setInstanceId(newSumKeep.getInstanceId());
			List<InsuranceCalculation> insuranceCalculations = insuranceCalculationService.selectInsuranceCalculationList(insuranceCalculation);
			wfsLimitSetUpdto.setInsuranceCalculationList(insuranceCalculations);
			wfsLimitSetUpdto.setNewSumList(newSumList);
			return AjaxResult.success(wfsLimitSetUpdto);*/
		}


		BigDecimal rate =null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		NewSum newSum1 = newSumService.selectNewSumById(newSumKeep.getId());
		InsuranceCalculation insuranceCalculation = new InsuranceCalculation();
		insuranceCalculation.setInstanceId(newSumKeep.getInstanceId());
		List<InsuranceCalculation> insuranceCalculations = insuranceCalculationService.selectInsuranceCalculationList(insuranceCalculation);
		if(insuranceCalculations!=null && insuranceCalculations.size()>0 ){
			InsuranceCalculation calculation = insuranceCalculations.get(0);
			if(StringUtils.isNotEmpty(calculation.getPlanRate())){
				if(calculation.getPlanRate().contains("%")) {
					String replace = calculation.getPlanRate().replace("%", "");
					rate = new BigDecimal(replace).divide(new BigDecimal(100));
				}else{
					rate = new BigDecimal(calculation.getPlanRate());
				}
			}
		}
		//查询费率
		Map<String, Object> rates = newSumKeepMapper.getRate(newSum1.getSector());
		String oldMinRate = rates.get("oldMinRate").toString();
		String oldMaxRate = rates.get("oldMaxRate").toString();
		String minRate = rates.get("minRate").toString();
		String maxRate = rates.get("maxRate").toString();

		//查询老的是不是相等
		if(rate.compareTo(new BigDecimal(oldMinRate))==0){
			//如果相等就要更新为最新费率
			rate = new BigDecimal(minRate);
		}else if(rate.compareTo(new BigDecimal(oldMaxRate))==0 ){
			rate = new BigDecimal(maxRate);
		}

		BigDecimal newRate = rate.multiply(new BigDecimal(100));
		BigDecimal bigDecimal = newRate.setScale(7, RoundingMode.HALF_UP);
		String s1 = Arith.removeZeros(bigDecimal.toString());
		String planRate =s1+"%";


		if(newSum1!=null && newSum1.getSumDay()!=null && newSum1.getStartDate()!=null && newSum1.getEndDate() !=null){
			String sumDay = newSum1.getSumDay();
			String newStartStr = sdf.format(newEffectiveDate);
			String endStr = sdf.format(newSum1.getEndDate());
			try {
				boolean run =false;
				List<String> yearList = DayUtils.getYearBetweenDate(newStartStr, endStr);
				List<String> runList = new ArrayList<>();
				for (String s : yearList) {
					runList.add(s+"-02-29");
				}
				if(runList.size()>0){
					List<String> everyday = DayUtils.getEveryday(newStartStr, endStr);
					for (String s : runList) {
						if(everyday.contains(s) && !endStr.equals(s)){
							run = true;
							System.out.println("闰年");
							break;
						}
					}
				}
				BigDecimal multiply = new BigDecimal(newSum1.getSum()).multiply(rate).setScale(10,BigDecimal.ROUND_HALF_UP);
				BigDecimal divide1 = new BigDecimal(0);
				if(run){
					divide1 = multiply.divide(new BigDecimal(366),BigDecimal.ROUND_HALF_UP).setScale(10,BigDecimal.ROUND_HALF_UP);
				}else{
					divide1 = multiply.divide(new BigDecimal(365),BigDecimal.ROUND_HALF_UP).setScale(10,BigDecimal.ROUND_HALF_UP);
				}
				//计算最新保费
				int i2 = DayUtils.daysBetween(newStartStr, endStr);
				BigDecimal newSumDay = divide1.multiply(new BigDecimal(i2+1)).setScale(2, BigDecimal.ROUND_HALF_UP);
				NewSum newSum = new NewSum();
				newSum.setId(newSumKeep.getId());
				newSum.setStartDate(newEffectiveDate);
				newSum.setSumDay(newSumDay.toString());
				if(sumDay.equals("-")){
					newSum.setSumDay("-");
				}
				newSumService.updateNewSum(newSum);
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		NewSum newSum = new NewSum();
		newSum.setInstanceId(newSumKeep.getInstanceId());
		List<NewSum> newSumList = newSumService.selectNewSumList(newSum);
		wfsLimitSetUpdto.setNewSumList(newSumList);
		//重新计算
		BigDecimal sumAmt = BigDecimal.ZERO;
		String dealerName = "";
		String sectorName = "";
		if(newSum1.getSumDay()!=null && !newSum1.getSumDay().equals("-")){
			for (NewSum sum : newSumList) {
				if(sum.getSumDay() != null){
					sumAmt = sumAmt.add(new BigDecimal(sum.getSumDay()));
				}
				dealerName = sum.getDealerName();
				sectorName = sum.getSector();
			}
		}
		//查询是否补缴的保费
		PaidSum paidSum = new PaidSum();
		paidSum.setInstanceId(newSumKeep.getInstanceId());
		List<PaidSum> paidSums = paidSumService.selectPaidSumList(paidSum);
		if(paidSums!=null && paidSums.size()>0){
			//查询费率旧
			NewSumKeep sumKeep = new NewSumKeep();
			sumKeep.setDealerName(newSum1.getDealerName());
			sumKeep.setSector(newSum1.getSector());
			List<NewSumKeep> newSumKeeps = newSumKeepService.selectNewSumKeepList4(sumKeep);
			BigDecimal rateOld = null;
			if(newSumKeeps!=null && newSumKeeps.size()>0){
				String planRate1 = newSumKeeps.get(0).getPlanRate();
				rateOld = new BigDecimal(planRate1);
			}
			if(rateOld !=null){
				for (PaidSum sum : paidSums) {
					paidSumService.deletePaidSumById(sum.getId());
				}
				NewSumKeep newSumKeep1 = new NewSumKeep();
				newSumKeep1.setOldPlanRate(rateOld.toString());
				newSumKeep1.setPlanRate(rate.toString());
				newSumKeep1.setDealerName(newSum1.getDealerName());
				newSumKeep1.setSector(newSum1.getSector());
				List<PaidSum> list = newSumKeepService.selectNewSumKeepList(newSumKeep1);
				if(list!=null && list.size()>0){
					for (PaidSum sum : list) {
						sum.setId(IdUtils.simpleUUID());
						sum.setInstanceId(newSumKeep.getInstanceId());
						sum.setRate(planRate);
						paidSumService.insertPaidSum(sum);
					}
				}
				wfsLimitSetUpdto.setPaidSumList(list);
				for (PaidSum sum : list) {
					if(sum.getPaidsum()!=null){
						sumAmt = sumAmt.add(new BigDecimal(sum.getPaidsum()));
					}
				}
			}
		}
		if(insuranceCalculations!=null && insuranceCalculations.size()>0 ){
			for (InsuranceCalculation insuranceCalculation1 : insuranceCalculations) {
				insuranceCalculation1.setPlanRate(planRate);
				if(sumAmt.compareTo(new BigDecimal(0)) ==1){
					insuranceCalculation1.setPlanTotal(sumAmt.toString());
				}
				insuranceCalculationService.updateInsuranceCalculation(insuranceCalculation1);
			}
			wfsLimitSetUpdto.setInsuranceCalculationList(insuranceCalculations);
		}
		wfsLimitSetUpdto.setDealerName(dealerName);
		wfsLimitSetUpdto.setSectorName(sectorName);
		return AjaxResult.success(wfsLimitSetUpdto);
	}

	@ApiOperation("New Sum")
	@PostMapping("/newSum")
	public AjaxResult newSum(@RequestBody NewSumDTO newSumDTO) {
		boolean flag =false;
		ArrayList<NewSum> list = new ArrayList<>();
		List<LimitActiveProposal> limitActiveProposals = newSumDTO.getLimitActiveProposals();
		if(limitActiveProposals == null){
			return AjaxResult.success(list);
		}
		for (LimitActiveProposal limitActiveProposal : limitActiveProposals) {
			if(limitActiveProposal.getIsReplace() !=null && limitActiveProposal.getIsReplace()  == 1  && limitActiveProposal.getCurrentActiveLimitExpiryDate() !=null
					&& limitActiveProposal.getCurrentActiveLimit() != null
			){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				try {
					Date parse = sdf.parse(limitActiveProposal.getCurrentActiveLimitExpiryDate());
					limitActiveProposal.setProposedEnd(parse);
				}catch (Exception e){
					e.printStackTrace();
				}

				limitActiveProposal.setProposalActiveLimit(limitActiveProposal.getCurrentActiveLimit());
			}
		}
		List<LimitActiveProposal> TemplimitActiveProposals = new ArrayList<>();
		List<LimitActiveProposal> newLimitActiveProposals = new ArrayList<>();
		//这里将Temp分出来
		for (LimitActiveProposal limitActiveProposal : limitActiveProposals) {
			if(limitActiveProposal.getLimitType().equals("TEMP")){
				if(limitActiveProposal.getProposalActiveLimit()!=null){
					String amt = limitActiveProposal.getProposalActiveLimit().replace(",", "");
					if(Double.valueOf(amt)>0){
						TemplimitActiveProposals.add(limitActiveProposal);
					}
				}
			}else{
				if(!limitActiveProposal.getLimitType().equals("PART")){
					String amt = limitActiveProposal.getProposalActiveLimit().replace(",", "");
					if(Double.valueOf(amt)>0){
						newLimitActiveProposals.add(limitActiveProposal);
					}
				}
			}
			try {
				Long aLong = Long.valueOf(limitActiveProposal.getProposalActiveLimit());
			}catch (Exception e){
				e.printStackTrace();
				throw  new BaseException("激活额度应为整数");
			}
		}
		List<NewSumKeep> insuranceCalculations = newSumDTO.getInsuranceCalculations();
		String planRate = insuranceCalculations.get(0).getPlanRate();
		BigDecimal rate =null;
		String planMethod = insuranceCalculations.get(0).getPlanMethod();
		if(planMethod.equals("缴纳保费")){
			if(StringUtils.isEmpty(planRate)){
				throw  new BaseException("请选择费率");
			}
			if(planRate.contains("%")) {
				String replace = planRate.replace("%", "");
				rate = new BigDecimal(replace).divide(new BigDecimal(100));
			}else{
				rate = new BigDecimal(planRate);
			}
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		DecimalFormat df = new DecimalFormat("0");
		List<NewSum> newSumList = new ArrayList<>();
		String dealerName = limitActiveProposals.get(0).getDealerName();
		String sector = limitActiveProposals.get(0).getSector();
		Date proposedStart = limitActiveProposals.get(0).getProposedStart();
		if(newLimitActiveProposals!=null && newLimitActiveProposals.size()>0 ){
			List<NewSum> newSums = newSumKeepService.newSums(newLimitActiveProposals, rate, dealerName, sector, flag,false,planMethod);
			if(newSums!=null && newSums.size()>0){
				for (NewSum newSum : newSums) {
					newSum.setTempLimit("N");
					newSum.setInsuranceNo("");
				}
			}
			if(TemplimitActiveProposals!=null && TemplimitActiveProposals.size()>0){
				List<NewSum> newSumsT = newSumKeepService.newSums(TemplimitActiveProposals, rate, dealerName, sector, flag,true,planMethod);
				if(newSumsT!=null && newSumsT.size()>0){
					for (NewSum newSum : newSumsT) {
						newSum.setTempLimit("Y");
						newSum.setInsuranceNo("");
					}
				}
				newSums.addAll(newSumsT);
			}
			list.addAll(newSums);
		}
		return AjaxResult.success(list);
	}

	public boolean isBetween(Date start,Date end,Date date){
		if(date.getTime()<=end.getTime() && date.getTime()>=start.getTime()){
			return true;
		}else {
			return false;
		}
	}

	public static long countDay(String begin,String end){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date beginDate , endDate;
		long day = 0;
		try {
			beginDate= format.parse(begin);
			endDate= format.parse(end);
			day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return day;
	}

	public AjaxResult getDeposit(@RequestBody DepositDecreaseDTO depositDecreaseDTO) throws IOException {
		JSONObject jsonObject = new JSONObject();
		List<String[]> dealerCodeArr = depositDecreaseDTO.getDealerCodeArr();
		jsonObject.put("DealerCode", depositDecreaseDTO.getDealerCodeArr());
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//        HttpPost httpPost = new HttpPost("http://10.226.186.86:8081/CreditLoanSuspenseAPIUAT7/CreditInfo");
		HttpPost httpPost = new HttpPost(wfsUrl + "SuspenseInfo");
		httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
		StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
		entity.setContentType("application/json;charset=UTF-8");
		entity.setContentEncoding("UTF-8");
		httpPost.setEntity(entity);
		httpPost.setHeader("Accept", "application/json, text/plain, */*");
		httpPost.setHeader("Accept-Encoding", "gzip, deflate");
		httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38");
		Map<String, Object> objectList = new HashMap<>();
		List<Map<String, String>> maps = new ArrayList<>();
		ArrayList<String> stringNew = new ArrayList<>();
		ArrayList<String> stringOld = new ArrayList<>();
		try {
			HttpResponse response = httpClient.execute(httpPost);
			String responseStr = EntityUtils.toString(response.getEntity());
			log.info("WFS外部接口数据返回结果=[{}]", responseStr);
			objectList = JSONObject.parseObject(responseStr, Map.class);
			log.info("WFS外部接口数据返回JSON结果=[{}]", JSON.toJSONString(responseStr));
			try{
              /*  stringObjectHashMap = JSONObject.parseObject(String.valueOf(JSONObject.parseObject(String.valueOf(JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(objectList.get("Data"))).get(0))).get(0)))), Map.class);
                System.out.println(stringObjectHashMap);*/
				Object data = objectList.get("Data");
				JSONArray data1 = JSONObject.parseArray(JSONObject.toJSONString(objectList.get("Data")));
				if(data1!=null && data1.size()>0){
					for (Object o : data1) {
						System.out.println(o);
						JSONArray data2 = JSONObject.parseArray(JSONObject.toJSONString(o));
						if(data2!=null && data2.size()>0){
							for (Object o1 : data2) {
								Map<String, Object>  stringObjectHashMap =  JSONObject.parseObject(JSONObject.toJSONString(o1),Map.class);
								if(stringObjectHashMap != null && stringObjectHashMap.get("DealerCode")!=null && stringObjectHashMap.get("SuspenseInfo")!=null ){
									Map<String, Object>  suspenseInfo = JSONObject.parseObject(JSONObject.toJSONString(stringObjectHashMap.get("SuspenseInfo")), Map.class);
									if(suspenseInfo!=null && suspenseInfo.get("Deposit")!=null){
										HashMap<String, String> stringStringHashMap = new HashMap<>();
										stringStringHashMap.put("DealerCode",stringObjectHashMap.get("DealerCode").toString());
										stringNew.add(stringObjectHashMap.get("DealerCode").toString());
										stringStringHashMap.put("Deposit",suspenseInfo.get("Deposit").toString());
										if(suspenseInfo.get("CBDeposit")!=null){
											stringStringHashMap.put("CBDeposit",suspenseInfo.get("CBDeposit").toString());
										}
										if(suspenseInfo.get("PartDeposit")!=null){
											stringStringHashMap.put("PartDeposit",suspenseInfo.get("PartDeposit").toString());
										}
										if(suspenseInfo.get("UsedDeposit")!=null){
											stringStringHashMap.put("UsedDeposit",suspenseInfo.get("UsedDeposit").toString());
										}
										stringStringHashMap.put("TEMPDeposit","-");
										maps.add(stringStringHashMap);
									}
								}
							}
						}
					}
				}
			}catch (NullPointerException e){
				e.printStackTrace();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		List<String[]> dealerCodeArr1 = depositDecreaseDTO.getDealerCodeArr();
		for (String[] strings : dealerCodeArr1) {
			if(strings!=null && strings.length>0){
				for (String string : strings) {
					stringOld.add(string);
				}
			}
		}
		if(stringOld.size()>stringNew.size()){
			stringOld.removeAll(stringNew);
			if(stringOld.size()>0){
				for (String s : stringOld) {
					HashMap<String, String> stringStringHashMap = new HashMap<>();
					stringStringHashMap.put("DealerCode",s);
					stringStringHashMap.put("Deposit","");
					stringStringHashMap.put("CBDeposit","");
					stringStringHashMap.put("PartDeposit","");
					stringStringHashMap.put("UsedDeposit","");
					stringStringHashMap.put("TEMPDeposit","-");
					maps.add(stringStringHashMap);
				}
			}
		}
		return AjaxResult.success(maps);
	}

}
